<?php
/**
 * Created by liecol on 2015/6/12.
 */
class MitaskAction extends Action {

	/**
	 * [getMitaskById 任务列表]
	 * @param  [type]  $name   [名称]
	 * @param  [type]  $status [状态]
	 * @return [type]          [objArray]
	 */
	public function getMitaskList($name=null,$status=null,$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$condition['deleted'] = 0;
		if ($name) {
				$condition['name'] = array('like',"%{$name}%");
			}
		if ($name) {
				$condition['status'] = $status;
			}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		Session::switchCustomer($customerId);
		$arr = $MitaskModel->where($condition)->order("updateTime DESC")->limit("$start, $limit")->select();
		if ($arr) {
				$count=$MitaskModel->where($condition)->order("updateTime DESC")->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}	
	}

	/**
	 * [getMitaskById 拿取具体任务信息]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function getMitaskById($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		$QuanModel = M("miyouquan");
		Session::switchCustomer($customerId);
		$condition['id'] = $id;
		$oldData = $MitaskModel->where($condition)->find();
		$qids = explode(',', $oldData['qids']);
		$str = '';
		foreach ($qids as $key => $value) {
			$qwhere['id'] = $value;
			$qname = $QuanModel->where($qwhere)->field("name")->select();
			if (count($qname)>0) {
				$str .= $qname[0]['name'].',';
			}
		}
		$qnames = substr($str,0,-1);
		$oldData['qnames'] = $qnames;
		if ($oldData) {
			Output::instance()->object($oldData);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * [MitaskAdd 增加任务]
	 * @param [type] $name              [名称]
	 * @param [type] $description       [任务描述]
	 * @param [type] $rewardDescription [奖励描述]
	 * @param [type] $startTime         [任务开始日期]
	 * @param [type] $endTime           [任务结束日期]
	 * @param [type] $status            [任务状态(1,正常，0，暂停)]
	 * @param [type] $jsonStr           [任务配置]
	 * @param [type] $startUrl          [任务领取url]
	 */
	public function MitaskAdd($name=null,$description=null,$rewardDescription=null,$startTime=null,$endTime=null,$status=null,$jsonStr=null,$startUrl=null,$maxNum=null,$qids=null,$uids=null,$goaldesc=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		Session::switchCustomer($customerId);
		$time = date("Y-m-d H:i:s");
		$data["name"] = $name;
		$data["description"] = $description;
		$data["goaldesc"] = $goaldesc;
		$data["rewardDescription"] = $rewardDescription;
		$data["startTime"] = $startTime;
		$data["endTime"] = $endTime;
		$data["status"] = $status;
		$data["jsonStr"] = $jsonStr;
		$data["startUrl"] = $startUrl;
		$data["maxNum"] = $maxNum;
		$data["qids"] = $qids;
		$data["estate"] = 0;
		$data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["deleted"] = 0;
		$result = $MitaskModel->add($data);
		if ($result !== false) {
			  $data["id"] = $result;
			  Output::instance()->object($data);
		} else {
			  Output::instance()->resultCode(code_sql_error);
		}	
	}

	/**
	 * [MitaskSave 编辑任务]
	 * @param [type] $id                [任务id]
	 * @param [type] $name              [名称]
	 * @param [type] $description       [任务描述]
	 * @param [type] $rewardDescription [奖励描述]
	 * @param [type] $startTime         [任务开始日期]
	 * @param [type] $endTime           [任务结束日期]
	 * @param [type] $status            [任务状态(1,正常，0，暂停)]
	 * @param [type] $jsonStr           [任务配置]
	 * @param [type] $startUrl          [任务领取url]
	 */
	public function MitaskSave($id,$name=null,$description=null,$rewardDescription=null,$startTime=null,$endTime=null,$status=null,$jsonStr=null,$startUrl=null,$maxNum=null,$qids=null,$uids=null,$goaldesc=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		Session::switchCustomer($customerId);
		$time = date("Y-m-d H:i:s");
		$data["name"] = $name;
		$data["description"] = $description;
		$data["goaldesc"] = $goaldesc;
		$data["rewardDescription"] = $rewardDescription;
		$data["startTime"] = $startTime;
		$data["endTime"] = $endTime;
		$data["status"] = $status;
		$data["jsonStr"] = $jsonStr;
		$data["startUrl"] = $startUrl;
		$data["maxNum"] = $maxNum;
		$data["qids"] = $qids;
		$data["estate"] = 0;
		$data["updateTime"] = $time;
		$where['id'] = $id;
		$where['deleted'] = 0;
		$result = $MitaskModel->where($where)->save($data);
		if ($result !== false) {
			$data["id"] = $result;
			Output::instance()->object($data);
		}else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public function setDefault($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		Session::switchCustomer($customerId);
		$MitaskModel->startTrans();
		$success1=$MitaskModel->query("update wx_mitask set isDefault=0 where isDefault=1");
		$success2=$MitaskModel->query("update wx_mitask set isDefault=1 where id=$id");
		if ($success1 !== false && $success2!==false) {
			$MitaskModel->commit();
			Output::instance()->resultCode(code_success);
		} else {
			$MitaskModel->rollback();
			Output::instance()->resultCode(code_sql_error);
		}	
	}
	/**
	 * [MitaskDel 删除任务]
	 * @param [type] $id      [任务id]
	 */
	public function MitaskDel($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		Session::switchCustomer($customerId);
		$where['id'] = $id;
		$where['deleted'] = 0;
		$data['deleted'] = 1;
		$result = $MitaskModel->where($where)->save($data);
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

	}

	/**
	 * [getmishareList 获取分享元素]
	 * @param [type] $id      [任务id]
	 */
	public function getmishareList($title=null,$description=null,$module=null,$start=0,$limit=10)
	{
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MishareModel = M("mishare");
		Session::switchCustomer($customerId);
		$condition['sha.module'] = array('in', array('product', 'micontent','shenqi'));
		if ($title) {
			$condition['sharem.title'] = array('like',"%{$title}%");
		}
		if ($description) {
			$condition['sharem.description'] = array('like',"%{$description}%");
		}
		if ($module) {
			$condition['sha.module'] = array('like',"%{$module}%");
		}
		$arr = $MishareModel->alias('sha')
			->join("LEFT JOIN  wx_mishare_material as sharem ON sha.id = sharem.sId")
			->field('sha.module,sha.id,sha.moduleId,sharem.title,sharem.description')
			->where($condition)
			->limit("$start, $limit")
			->select();
		if ($arr) {
			$count = $MishareModel->alias('sha')
				->join("LEFT JOIN  wx_mishare_material as sharem ON sha.id = sharem.sId")
				->field('sha.module,sha.moduleId,sharem.title,sharem.description')
				->where($condition)
				->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}

	}

		/**
	 * [getmishareDetail 任务详情]
	 * @param [type] $id                [任务id]
	 * @param [type] $start             []
	 * @param [type] $limit       		[]
	 */
	public function getmishareDetail($id,$qname=null,$fullName=null,$status=null,$rewardType=null,$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MitaskModel = M("mitask_user");
		Session::switchCustomer($customerId);
		$condition['tasku.tId'] = $id;
		if ($qname) {
			$condition['quan.name'] = array('like',"%{$qname}%");
		}
		if ($fullName) {
			$condition['au.fullName'] = array('like',"%{$fullName}%");
		}
		if ($status) {
			$condition['tasku.status'] = $status;
		}
		if ($rewardType) {
			$condition['tasku.rewardType'] = $rewardType;
		}
		$arr = $MitaskModel->alias('tasku')
			->join("LEFT JOIN  wx_all_user as au ON au.id = tasku.uId")
			->join("LEFT JOIN  wx_miyouquan as quan ON quan.id = tasku.qId")
			->where($condition)
			->field('tasku.id,tasku.status,tasku.reward,tasku.rewardType,tasku.createTime,tasku.completeTime,quan.name as qname, au.fullName')
			->limit("$start, $limit")
			->select();
		if ($arr) {
			$count = $MitaskModel->alias('tasku')
				->join("LEFT JOIN  wx_all_user as au ON au.id = tasku.uId")
				->join("LEFT JOIN  wx_miyouquan as quan ON quan.id = tasku.qId")
				->where($condition)
				->field('tasku.id,tasku.status,tasku.reward,tasku.rewardType,tasku.createTime,tasku.completeTime,quan.name as qname, au.fullName')
				->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}

	}
	public function setTplNotice($template_id,$tid,$uid,$qid,$toUser,$data){
		$platCustomerId=C("PLANT_CUSTOMERID");
		$TemplateModel = M("template_messages");
		Session::switchCustomer(0);
		$TrecodeModel = M("mitask_record");
		Session::switchCustomer($platCustomerId);

		$rwhere['tId'] = $tid;
		$rwhere['uId'] =$uid;
		$result = $TrecodeModel->where($rwhere)->find();

		if(!$result) {
			$url = C("SERVER_HOST") . "call.html?customerId=".$platCustomerId."&module=task&method=index&params=%7B%22tId%22:$tid,%22qId%22:$qid%7D";
			$url = urlencode($url);					
			$topcolor = "#FF0000";
			//data得转json
			$apiresult=WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
			if ($apiresult->errcode ==0) {
				$rdata['tId'] = $tid;
				$rdata['uId'] = $uid;
				$rdata['sendType']=1;
				$result = $TrecodeModel->add($rdata);
			}
		}
	}
	public function sendServiceMotice($toUser,$tid,$uid,$qid,$data){
		$platCustomerId=C("PLANT_CUSTOMERID");
		$TemplateModel = M("template_messages");
		Session::switchCustomer(0);
		$TrecodeModel = M("mitask_record");
		Session::switchCustomer($platCustomerId);

		$rwhere['tId'] = $tid;
		$rwhere['uId'] =$uid;
		$result = $TrecodeModel->where($rwhere)->find();
		if($result){
			$out=new stdClass();
			$out->errcode=0;
			return $out;
		}
		$articles=array();
		$article=new stdClass();
		$article->title=urlencode("新任务提醒");
		$url = C("SERVER_HOST") . "call.html?customerId=".$platCustomerId."&module=task&method=index&params=%7B%22tId%22:$tid,%22qId%22:$qid%7D";
		$text=$data["first"]["value"]."\n任务内容：".$data["keyword1"]["value"]
			."\n截止时间：".$data["keyword2"]["value"]
			."\n".$data["remark"]["value"];
		$article->description=urlencode($text);
		$url = urlencode($url);	
		$article->url=$url;
		$article->picurl="";
		array_push($articles, $article);
		$result=WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
		//if ($result->errmsg == 'ok') {
			$rdata['tId'] = $tid;
			$rdata['uId'] = $uid;
			$rdata['sendType']=2;
			$result = $TrecodeModel->add($rdata);
		//}
		return $result;
	}
	/**
	 * [sendtaskList 定时发送任务]
	 * @return [type] [description]
	 */
	public function sendtaskList($param=null,$task=null){
		$platCustomerId=C("PLANT_CUSTOMERID");
		$TemplateModel = M("template_messages");
		Session::switchCustomer(0);
		$MitaskModel = M("mitask");
		$MitaskUserModel = M("mitask_user");
		$QuanuserModel = M("quan_user");
		$TrecodeModel = M("mitask_record");
		Session::switchCustomer($platCustomerId);
		$where['deleted'] = 0;
		$where['status'] = 1;
		$time = date("Y-m-d H:i:s");
		$where['startTime'] = array('elt', $time);
		$where['endTime'] = array('egt', $time);
		$sql = "SELECT * from wx_".$platCustomerId."_template_messages where status = 'mitask' limit 1";
		$templatemsg = $QuanuserModel->query($sql);
		if (count($templatemsg)>0) {
			$templateId = $templatemsg[0]['templateId'];
		}
		if(!$param) { //如果没有参数，是定时任务执行
			$tarr = $MitaskModel->where($where)->select();
			foreach ($tarr as $key => $value) {
				$tid=$value['id'];
				$jsonStr = json_decode($value['jsonStr']);
				$starttitle = $jsonStr->TEMPLETE->TASK_FIRST;
				$overtitle = $jsonStr->TEMPLETE->TASK_REMARK;
				if ($templateId) {
					$data['first'] = array('value'=> "$starttitle",'color'=>"#743A3A");
					$data['remark'] = array('value'=> "$overtitle","color"=>'#008000');
				}

				$taskUserCount=$MitaskUserModel->where("tId=$tid")->count();
				if($taskUserCount >= $value["maxNum"]) {
					continue;
				}
				$sendType=$jsonStr->SENDTYPE;
				if($sendType==1) {
					continue;
				}	
				if ($jsonStr->FRONT->KEY && $jsonStr->FRONT->KEY == "NO" && $value['estate'] !== 1) {
					$tdata['estate'] = 1;
					$twhere['id'] = $value['id'];
					$result = $MitaskModel->where($twhere)->save($tdata);
					if ($result !== false) {
							$lastTime=strtotime("-48 hour");
							$lastTime=date('Y-m-d H:i:s',$lastTime);
							$qwhere['quser.qid'] = array("in",$value['qids']);
							$qwhere['quser.deleted'] = array("eq",0);
							$qwhere['user.status'] = array("neq","unsubscribe"); //排除未关注用户
							$qwhere['user.lastTime'] = array("egt",$lastTime);
							$data['keyword1'] = array('value'=> $value['name'],'color'=>'#173177');
							$data['keyword2'] = array('value'=> $value['endTime'],'color'=>'#173177');

							$arr = $QuanuserModel->alias('quser')
									->join("INNER JOIN  wx_all_user as au ON au.id = quser.uid")
									->join("INNER JOIN  wx_".$platCustomerId."_user_weixin_info as info ON info.id = au.weixinUserId")
									->join("INNER JOIN wx_".$platCustomerId."_user as user on user.userName=info.openid")
									->where($qwhere)
									->field("info.openid,au.id,quser.qid,au.id as uid")
									->select();
							if ($arr) {
								foreach ($arr as $k1 => $v1) {
									$uid=$v1["uid"];
									$toUser = $v1['openid'];
									$qid = $v1['qid'];
									self::sendServiceMotice($toUser,$tid,$uid,$qid,$data);
								}	
							}
							$tdata['estate'] = 2;
							$result = $MitaskModel->where($twhere)->save($tdata);
						}
					}
				}
		} else { //触发任务
			$data['keyword1'] = array('value'=> $task['name'],'color'=>'#173177');
			$data['keyword2'] = array('value'=> $task['endTime'],'color'=>'#173177');
			$jsonStr = json_decode($task['jsonStr']);
			$starttitle = $jsonStr->TEMPLETE->TASK_FIRST;
			$overtitle = $jsonStr->TEMPLETE->TASK_REMARK;
			if ($templateId) {
					$data['first'] = array('value'=> "$starttitle",'color'=>"#743A3A");
					$data['remark'] = array('value'=> "$overtitle","color"=>'#008000');
			}
			$tid=$task["id"];
			$uid=$param->miUId;
			$qid=$param->qId;
			$user = $QuanuserModel->alias('quser')
						->join("INNER JOIN  wx_all_user as au ON au.id = quser.uid")
						->join("INNER JOIN  wx_".$platCustomerId."_user_weixin_info as info ON info.id = au.weixinUserId")
						->where("au.id=$uid")
						->field("info.openid,au.id,quser.qid,au.id as uid")
						->find();
			if($user) {
				$toUser=$user["openid"];
				self::setTplNotice($templateId,$tid,$uid,$qid,$toUser,$data);
			}
		}
	}

}